<?php


namespace app\yperp\logic;

use app\yperp\model\Brand;
use app\yperp\model\Supplier;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client as GuzzleHttpClient;
use think\Db as ThinkDb;
use app\yperp\model\Brand as BrandModel;
use Fastposter\Client;
use app\admin\model\Attachment as AttachmentModel;
use think\Db;
use think\Image;

class ConflateMainImg
{
    private static $instance;
    protected  $token;
    public static function getInstance()
    {
        if (!defined('PUBLIC_PATH')) {
            define('PUBLIC_PATH', '/');
        }
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    function error($str = '')
    {
        if (php_sapi_name() !== 'cli') {
            dump($str);
            die;
        } else {
            dump($str);
        }
    }
    public function conflate($goods_id = null)
    {
        if ($goods_id === null) return $this->error('缺少参数');

        $goods = Supplier::where(['id' => $goods_id])->where('status >  0')->find();

        $Brand = Brand::where(['id' => $goods['brand_id']])->find();

        if (!$Brand) {
            $this->error('logo不存在，请上传logo后再试！');
        }
        $logo_path = get_file_path($Brand['logo']);
        if (!($goods['goods_main_image_temp'] > 0)) {
            $this->error('主图不存在，请上传后再试！');
        }


        $goods_main_image = get_file_path($goods['goods_main_image_temp']);
        dump([$logo_path,$goods_main_image]);
        // die;
        $params = [
            "logo" =>  'http://host.docker.internal' . $logo_path,
            "goods" =>  'http://host.docker.internal' . $goods_main_image,
        ];


        if ($Brand['design_code'] == null) {

            $default_design_code =   module_config('yperp.default_design_code');

            if (!$default_design_code) {
                $this->error('默认设计ID未设置');
            } else {
                $Brand['design_code'] = $default_design_code;
            }
        }
        $sqlite_param = [
            "logo" =>  'http://erp.lhp' . $logo_path,
            "goods" =>  'http://erp.lhp' . $goods_main_image,
            'code' => $Brand['design_code'],
            'title' => $goods['goods_title_alias'] . ' ' . $goods['goods_color_alias'],
            // 'height_price' => '某东价：' . $goods['sell_market_price'] . '元',
            // 'buy_price' =>  '虹创秒杀价：' . $goods['sell_daily_price'] . '元',
        ];


        if ($goods['sell_daily_price']) {
            $sqlite_param['buy_price'] = '虹创秒杀价：' . $goods['sell_daily_price'] . '元';
        } else {
            $sqlite_param['buy_price'] = '';
        }

        if ($goods['sell_market_price']) {
            if ($sqlite_param['buy_price']) {
                $sqlite_param['height_price'] = '某东价：' . $goods['sell_market_price'] . '元';
            } else {
                $sqlite_param['height_price'] = '虹创秒杀价：' . $goods['sell_market_price'] . '元';
            }
        } else {
            $sqlite_param['height_price'] = '';
        }

        $this->get_db_sqlite($sqlite_param);

        $save = env('root_path') . 'public' . DIRECTORY_SEPARATOR . 'goods.png';
        # 1.创建海报客户端对象
        $client = new Client("fastposter-token", "http://127.0.0.1:5001");
        # 3.生成海报并保存(提供图片流、二进制、base64等多种方式)
        $filename = $client->buildPoster($Brand['design_code'], $params)->save($save);

        // echo '<img src="' . DIRECTORY_SEPARATOR . 'goods.png" />';die;
        $res = $this->saveImage($filename);

        if ($res) {
            Supplier::where(['id' => $goods_id])->update(['goods_main_image' => $res['id']]);
        }
    }

    private function saveImage($imagePath)
    {
        $dir_name = date('Ymd');
        $file_dir = config('upload_path') . DIRECTORY_SEPARATOR . 'images/' . $dir_name . '/';
        if (!is_dir($file_dir)) {
            mkdir($file_dir, 0766, true);
        }
        pathinfo($imagePath, PATHINFO_FILENAME);
        $new_file = $file_dir . DIRECTORY_SEPARATOR . md5_file($imagePath) . '.' . pathinfo($imagePath, PATHINFO_EXTENSION);
        rename($imagePath, $new_file);
        // 获取附件信息
        $uid = php_sapi_name() !== 'cli' ? session('user_auth.uid') : 1;
        $file_info = [
            'uid' => $uid,
            'name' => pathinfo($new_file, PATHINFO_FILENAME),
            'mime' => mime_content_type($new_file),
            'path' =>  str_replace('\\', '/', str_replace(env('root_path') . 'public\\', '', $new_file)),
            'ext' => pathinfo($new_file, PATHINFO_EXTENSION),
            'size' => filesize($new_file),
            'md5' => md5_file($new_file),
            'sha1' => sha1_file($new_file),
            'thumb' => '',
            'module' => 'yperp',
            'width' => getimagesize($new_file)[0],
            'height' => getimagesize($new_file)[1],
        ];

        return AttachmentModel::create($file_info);
    }


    private function get_db_sqlite($data = [], $Sqlite_file = '')
    {
        if ($Sqlite_file == '') {
            $Sqlite_file = module_config('yperp.fastposter_sqlite_path');
            if (!$Sqlite_file) {
                $this->error('fastposter设计器数据库地址未设置');
            }
        }
        $config = [
            // 数据库类型
            'type' => 'sqlite',
            // 数据库连接DSN配置
            'dsn' => 'sqlite:' . $Sqlite_file,
            // 数据库编码默认采用utf8
            'charset' => 'utf8',
        ];


        $Sqlite =   Db::connect($config)->table("posters")->where(['code' => $data['code']])->value('json');
        if (!$Sqlite) {
            $this->error('设计ID不存在');
        }
        $SqliteDatas = json_decode($Sqlite, true);
        foreach ($SqliteDatas['items'] as   &$value) {
            if (isset($data[$value['vd']])) {

                $value['v'] = $data[$value['vd']];
            }
        }

        Db::connect($config)->table("posters")->where(['code' => $data['code']])->update(['json' => json_encode($SqliteDatas, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)]);
        return json_decode($Sqlite, true);
    }
}
